package com.hkzhao.shixun.service.impl;

import com.github.pagehelper.PageHelper;
import com.hkzhao.shixun.common.api.CommonResult;
import com.hkzhao.shixun.common.utils.JwtTokenUtil;
import com.hkzhao.shixun.common.utils.TokenTranslate;
import com.hkzhao.shixun.common.utils.TokenUtil;
import com.hkzhao.shixun.config.MyRedisConfig;
import com.hkzhao.shixun.dao.UserDao;
import com.hkzhao.shixun.mbg.mapper.*;
import com.hkzhao.shixun.mbg.model.*;
import com.hkzhao.shixun.service.DrawsLotteryService;
import com.hkzhao.shixun.service.XwoUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <h3>j2ee</h3>
 * <p>xwoUser服务具体实现类</p>
 *
 * @author : hkzhao
 * @date : 2020-06-05 16:47
 **/
@Service
public class XwoUserServiceImpl implements XwoUserService {
    private static final Logger LOGGER = LoggerFactory.getLogger(XwoUserServiceImpl.class);
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired(required = false)
    private XwouserMapper xwouserMapper;
    @Autowired(required = false)
    private UserpermissionMapper userpermissionMapper;
    @Autowired(required = false)
    private LotteryrecordMapper lotteryrecordMapper;
    @Autowired(required = false)
    private UserDao userDao;
    @Autowired
    private DrawsLotteryService drawsLotteryService;
    @Autowired
    private TokenTranslate tokenTranslate;
    @Autowired(required = false)
    private CoreuserMapper coreuserMapper;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.xwoUserAuthority}")
    private String xwoUserAuthority;
    @Autowired(required=false)
    private ActivityMapper activityMapper;
    @Override
    public CommonResult register(String username, String password, String phoneNumber) {
        if(username.length()==0){
            return CommonResult.failed("用户名不能为空");
        }
        if(password.length()==0){
            return CommonResult.failed("密码不能为空");
        }
        if(phoneNumber.length()==0){
            return CommonResult.failed("电话号码不能为空");
        }
        if (xwouserMapper.selectByPrimaryKey(username)!=null) return CommonResult.failed("用户名重复");
        String token_id =TokenUtil.GetGUID();
        Xwouser xwouser = new Xwouser();
        Userpermission userpermission = new Userpermission();
        Coreuser coreUser = new Coreuser();
        xwouser.setIntegral(0.0);xwouser.setPassword(passwordEncoder.encode(password));
        xwouser.setPhonenumber(phoneNumber);xwouser.setTokenid(token_id);
        xwouser.setUsername(username);userpermission.setCreatetime(new Date());
        userpermission.setValue(xwoUserAuthority);userpermission.setTokenid(token_id);
        coreUser.setPosition("0");coreUser.setTokenid(token_id);coreUser.setUsername(username);
        xwouserMapper.insert(xwouser);
        userpermissionMapper.insert(userpermission);
        coreuserMapper.insert(coreUser);
        return CommonResult.success("注册xwo用户成功");
    }
    //@Cacheable(value = MyRedisConfig.REDIS_KEY_DATABASE,key="'pms:account:'+#username",unless = "#result==null")
    @Override
    public String login(String username, String password) {
        String token = null;
        try {
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                throw new BadCredentialsException("密码不正确");
            }
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            token = jwtTokenUtil.generateToken(userDetails);
        }catch (AuthenticationException e){
            LOGGER.warn("登陆异常:{}",e.getMessage());
        }
        return token;
    }

    @Override
    public CommonResult addLotteryRecord(String recordId, String location, String actualName, String phoneNumber) {
        //userDao.FillInLotteryRecord(recordId, location, phoneNumber,actualName);
        Lotteryrecord lr=lotteryrecordMapper.selectByPrimaryKey(recordId);
        lr.setLocation(location);lr.setActualname(actualName);lr.setPhonenumber(phoneNumber);
        lotteryrecordMapper.updateByPrimaryKey(lr);
        return CommonResult.success("填写中奖记录信息成功");
    }
    @Cacheable(value = MyRedisConfig.REDIS_KEY_DATABASE,key="'pms:draws:'+#username",unless = "#result==null")
    @Override
    public List<Lotteryrecord> findLotteryRecord(String username, String activityId,int pageNum,int pageSize) {
        if(username.length()==0) {
            return new ArrayList<>();
        }
        LotteryrecordExample lotteryrecordExample = new LotteryrecordExample();
        lotteryrecordExample.createCriteria().andActivityidEqualTo(activityId).andUsernameEqualTo(username);
        PageHelper.startPage(pageNum,pageSize);
        return lotteryrecordMapper.selectByExample(lotteryrecordExample);
    }

    @Override
    public CommonResult DrawsLottery(HttpServletRequest httpServletRequest, String activityId) {
        String username = getXwoUserNameByToken(httpServletRequest);
        if(username.length()==0){
            return CommonResult.failed("请重新登录");
        }
        return drawsLotteryService.DrawsLottery(username,activityId);
    }

    @Override
    public String getXwoUserNameByToken(HttpServletRequest httpServletRequest){
        return tokenTranslate.GetUsernameByHeader(httpServletRequest);
    }
    @Override
    public List<Activity> getActivityby(String actid, String tag, String title, String status, int pageNum, int pageSize)
    {
        ActivityExample activityExample=new ActivityExample();
        ActivityExample.Criteria r=activityExample.createCriteria();r.andStatusEqualTo("1");
        ActivityExample.Criteria r2=activityExample.createCriteria();r2.andStatusEqualTo("2");
        if (actid!=null) {r.andActivityidEqualTo(actid);r2.andActivityidEqualTo(actid);}
        if (tag!=null) {r.andTagEqualTo(tag);r2.andTagEqualTo(tag);}
        if (title!=null) {r.andTitleEqualTo(title);r2.andTitleEqualTo(title);}
        if (title!=status) {r.andStatusEqualTo(status);r2.andStatusEqualTo(status);}
        activityExample.or(r2);
        PageHelper.startPage(pageNum,pageSize);
        return activityMapper.selectByExample(activityExample);
    }
}
